<template>
  <div>
    <el-upload
      v-loading="loading"
      class="components-file-upload"
      :class="{disabled: (!isMultiple && comsFileUploadImageList.length > 0)}"
      action="api/file/upload"
      :headers="comsFileUploadImageHeaders"
      list-type="picture-card"
      :file-list="comsFileUploadImageList"
      :on-success="comsFileUploadImageSuccess"
      :on-remove="comsFileUploadImageRemove"
      :on-preview="comsFileUploadImagePreview"
      :before-upload="comsFileUploadImageBefore"
      accept=".jpg, .jpeg, .png, .gif, .bmp, .pdf, .JPG, .JPEG, .PBG, .GIF, .BMP, .PDF"
      :multiple="isMultiple"
    >
      <i v-if="!(!isMultiple && comsFileUploadImageList.length > 0)" class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="comsFileUploadPreviewVisible" append-to-body>
      <img width="100%" :src="comsFileUploadPreviewImageUrl" alt>
    </el-dialog>
  </div>
</template>

<script>
import { setTimeout } from 'timers'
export default {
  props: {
    md5s: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false
    },
    callback: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      comsFileUploadImageHeaders: {
        Authorization: 'Bearer ' + this.$store.state.user.token
      },
      comsFileUploadPreviewVisible: false,
      comsFileUploadPreviewImageUrl: null,
      comsFileUploadImageList: [],
      hasDownloadOldImages: false,
      loading: false
    }
  },
  computed: {
    isMultiple: {
      get() {
        return this.multiple
      }
    }
  },
  watch: {
    async md5s(newVal) {
      if (this.md5s && this.md5s !== '' && !this.hasDownloadOldImages) {
        this.comsFileUploadImageList = await this.comsFileUploadImageGetUrl(
          this.md5s
        )
        this.hasDownloadOldImages = true
      } else {
        if (!this.md5s || this.md5s === '') {
          this.comsFileUploadImageList = []
        }
        this.hasDownloadOldImages = false
      }
    }
  },
  async created() {
    if (this.md5s && this.md5s !== '') {
      this.comsFileUploadImageList = await this.comsFileUploadImageGetUrl(
        this.md5s
      )
      this.hasDownloadOldImages = true
    } else {
      this.comsFileUploadImageList = []
    }
  },
  methods: {
    async comsFileUploadImageGetUrl(md5s) {
      if (!md5s || md5s === '') return []
      // let imageList = []
      // console.log(typeof (md5s))
      // if (typeof (md5s) === 'string') {
      //   imageList = [{ name: md5s, md5: md5s, url: this.$api.getDownloadServiceUrl(md5s) }]
      //   console.log(imageList)
      // } else {
      //   this.md5s.forEach(md5 => {
      //     imageList.push(
      //       { name: md5, md5: md5, url: this.$api.getDownloadServiceUrl(md5) }
      //     )
      //   })
      // }
      // return imageList
      this.loading = true
      const res = await this.$http({
        url: '/api/file/url',
        method: 'POST',
        data: { md5s: md5s }
      })
      this.loading = false
      if (res.code === 0) {
        return res.data.list
      }
      return []
    },
    comsFileUploadImageSuccess(res, file) {
      if (
        res.code === 0 &&
        res.data.success_list &&
        res.data.success_list.length > 0
      ) {
        let _md5s = []
        if (this.md5s && this.md5s !== '') {
          _md5s = this.md5s.split(',')
        }
        res.data.success_list.forEach(item => {
          _md5s.push(item.md5)
        })
        _md5s = _md5s.join(',')
        this.$emit('update:md5s', _md5s)
        if (this.callback) {
          this.$emit(this.callback, { md5s: _md5s })
        }
      } else {
        this.comsFileUploadImageRemove()
        this.$commonUtils.showErrorToast('文件上传失败')
      }
    },
    comsFileUploadImageRemove(res, fileList = []) {
      let _md5s = []
      fileList.forEach(item => {
        if (item.md5) {
          _md5s.push(item.md5)
        } else {
          if (item.response.data.success_list) {
            item.response.data.success_list.forEach(val => {
              _md5s.push(val.md5)
            })
          }
        }
      })
      if (_md5s.length === 0) this.comsFileUploadImageList = []
      _md5s = _md5s.join(',')
      setTimeout(() => {
        this.$emit('update:md5s', _md5s)
        if (this.callback) {
          this.$emit(this.callback, { md5s: _md5s })
        }
      }, 500)
    },
    comsFileUploadImagePreview(file) {
      this.comsFileUploadPreviewImageUrl = file.url
      this.comsFileUploadPreviewVisible = true
    },
    comsFileUploadImageBefore(file) {
      // let isJPG = false;
      // switch (file.type) {
      //   case "image/png":
      //     isJPG = true;
      //     break;
      //   case "image/jpeg":
      //     isJPG = true;
      //     break;
      //   default:
      //     isJPG = false;
      //     break;
      // }
      const isLt2M = file.size / 1024 / 1024 < 2
      // if (!isJPG) {
      //   this.$commonUtils.showErrorToast("图片只能是 JPG/JPEG/PNG 格式!");
      // }
      if (!isLt2M) {
        this.$commonUtils.showErrorToast('图片大小不能超过 2MB!')
      }
      return isLt2M // isJPG &&
    }
  }
}
</script>

<style lang="scss">
.components-file-upload {
  .el-upload--picture-card {
    height: 100px;
    width: 100px;
    line-height: 104px;
  }
  .el-upload-list--picture-card .el-upload-list__item {
    height: 100px;
    width: 100px;
  }
}
.disabled .el-upload--picture-card {
  display: none;
}
</style>
